package com.fjrz.bbxwj.main.host.side

import android.Manifest
import android.app.Activity
import android.content.Intent
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.fjrz.bbxwj.R
import com.fjrz.bbxwj.entity.ReportType
import com.fjrz.bbxwj.main.host.adpter.ReportImageAdapter
import com.fjrz.bbxwj.mode.vm.ReportViewModel
import com.fjrz.bbxwj.popup.BottomPickerPopup
import com.fjrz.bbxwj.popup.ProgressPopup
import com.module.lemlin.view.DialogHintPopup
import com.module.lemlin.mode.ViewModeActivity
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.code
import com.module.lemlin.rxhttp.msg
import com.tbruyelle.rxpermissions3.RxPermissions
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import kotlinx.android.synthetic.main.activity_main_report.*
import java.lang.StringBuilder
import java.util.*
import java.util.concurrent.ConcurrentLinkedQueue

class MainReportActivity : ViewModeActivity<ReportViewModel>() {

    companion object {
        private const val EXTRA_KEY_VIDEO_ID = "EXTRA_KEY_VIDEO_ID"
        fun open(activity: Activity, videoId: Int) {
            val intent = Intent(activity, MainReportActivity::class.java).apply {
                putExtra(EXTRA_KEY_VIDEO_ID, videoId)
            }
            activity.startActivity(intent)
        }
    }

    private val mReportImageAdapter: ReportImageAdapter = ReportImageAdapter()

    private val mVideoId: Int
        get() = intent.getIntExtra(EXTRA_KEY_VIDEO_ID, 0)

    private var mReportType: ReportType? = null

    private val mBottomCatePopup: BottomPickerPopup by lazy {
        BottomPickerPopup(context = this, onConfirm = { action, position ->

            val reportType: MutableList<ReportType> =
                viewModel.reportTypeLiveData.value?.httpData?.data
                    ?: return@BottomPickerPopup
            tvReportType.text = reportType[position].name
            mReportType = reportType[position]

            tvReportConfirm.isEnabled =
                !etReportContent.text.isNullOrEmpty() && mReportType != null
        })
    }


    private val mProgressPopup: ProgressPopup by lazy {
        ProgressPopup(context = this, onConfirm = {

        }, onCancel = {
            mProgressPopup.dismiss()
            viewModel.dispose.clear()
        })
    }

    private val hintPopup: DialogHintPopup by lazy {
        DialogHintPopup(context = this,
            onConfirm = {
                hintPopup.dismiss()
                finish()
            },
            onCancel = {

            })
    }

    private val mQueue: Queue<String> = ConcurrentLinkedQueue<String>()
    private val mStringBuilder: StringBuilder = StringBuilder()

    override fun viewModel(): ReportViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.activity_main_report

    override fun stateBar(): StatusBar {
        return StatusBar(isLightMode = true, view = flReportBar)
    }

    override fun initView() {
        ivReportBack.setOnClickListener { this.finish() }

        tvReportType.setOnClickListener {
            viewModel.reportTypeList()
        }

        tvReportConfirm.setOnClickListener {

            mQueue.clear()
            mReportImageAdapter.data.filter {
                it !is Int
            }.forEach { mQueue.add(it.toString()) }

            if (mQueue.isNullOrEmpty()) {
                toast(message = "请选择图片")
            } else {
                mQueue.poll()?.let {
                    viewModel.commonUpload(it)
                }
            }
        }

        etReportContent.addTextChangedListener {
            tvReportConfirm.isEnabled = !it.isNullOrEmpty() && mReportType != null
        }

        rvReportImage.adapter = mReportImageAdapter.apply {
            setNewInstance(mutableListOf(R.mipmap.ic_17630))
        }
        mReportImageAdapter.setOnItemClickListener { adapter, view, position ->
            if (position == mReportImageAdapter.data.size - 1) {
                val rxPermissions = RxPermissions(this)
                rxPermissions.request(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                ).subscribe {
                    if (!it) {
                        toast(message = "请到设置中开启相关权限")
                    } else {
                        Matisse.from((this))
                            .choose(MimeType.ofImage())
                            .countable((true))
                            .maxSelectable(5)
                            .imageEngine(GlideEngine())
                            .theme(R.style.Matisse_Zhihu1)
                            .forResult((100))
                    }
                }
            }
        }
        mReportImageAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (view.id == R.id.ivReportDelete) {
                mReportImageAdapter.removeAt(position)
            }
        }
    }

    override fun initViewMode() {

        viewModel.reportTypeLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.throwable?.code, response.throwable?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            val data: MutableList<String> = mutableListOf()
            response.httpData?.data
                ?.forEach { data.add(it.name) }
            mBottomCatePopup.setFillData(
                title = "请选择举报类型", pickers = data
            ).showPopupWindow()
        })

        viewModel.uploadLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status == Status.START) {
                if (!mProgressPopup.isShowing)
                    mProgressPopup.showPopupWindow()
                mProgressPopup.resetProgress()
            } else if (response.status == Status.FAILURE) {
                mProgressPopup.dismiss()
                toast(response.throwable?.code, response.throwable?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.let {
                mStringBuilder.append(it.url).append(",")
                val path: String? = mQueue.poll()
                if (path.isNullOrEmpty()) {
                    val type: Int = mReportType?.id ?: return@Observer
                    val content: String = etReportContent.text.toString()
                    viewModel.reportSubmit(
                        mVideoId, type, content, mStringBuilder.toString()
                    )
                } else {
                    viewModel.commonUpload(path)
                }
            }
        })

        viewModel.progressLiveData.observe(this as LifecycleOwner, Observer { progress ->
            mProgressPopup.setProgress(progress)
        })

        viewModel.baseLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                mProgressPopup.dismiss()
                toast(response.throwable?.code, response.throwable?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            hintPopup.setTextTitle("提示")
                .setTextMessage(response.httpData?.msg ?: "提交成功，请等待平台审核处理")
                .setTextConfirm("好的")
                .isTextCancelGone((true))
                .setBackPressEnable(false)
                .setOutSideDismiss(false)
                .showPopupWindow()
        })
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && resultCode == RESULT_OK) {
            val pathList: MutableList<Any> = Matisse.obtainPathResult(data).toMutableList()
            if (pathList.size == 0)
                return
            pathList.add(R.mipmap.ic_17630)
            mReportImageAdapter.setNewInstance(pathList)
        }
    }
}